<?php
class Schedule extends MY_Controller
{
	var $form = '_elements/empty';
	var $curl = 'schedule';
	var $name = '';
	var $id_city;
	var $search = '';
	var $language;
	var $submenu = "_menu";	
		
	function __construct()
	{
		parent::__construct();
				
		$this->load->model(array('/public/contributor_model', '/public/company_model', '/public/marketplace_model', '/public/test_model', '/public/test_event_model', '/public/test_battery_model'));
 		
		// Load the nested sets "base" model
	    $this->load->model('/public/nested_sets_model');        
        // Load the purpose specific extension model class
        //$this->load->model('/public/article_model');
        $this->load->model('/public/category_model', 'cats');
        
		$this->validation->set_fields($this->test_event_model->fields);

		$this->data['Title'] = '';

		$this->language = parent::getLang();
		
		$this->name = '';
	}
	
	function index($id_test = null)
	{
		$this->data['id_event']  = $this->input->post('id_event');
		//die;
		$this->data['event'] = array();
		
		$fields = array('name' => T_('Category Name'));
        $this->data['treehtml'] = $this->cats->getTreeAsSchedule($fields);

        $config = array('id_companies' => $this->auth->getID());
		$this->data['battery_tests'] = array();//$this->test_model->searchBattery($config);
		
		$config = array('is_personal' => -1, 'id_users' => $this->auth->getID());
		$this->data['scheduled_tests'] = $this->test_model->searchSchedule($config);
		
		if($this->data['id_event'])
		{
			foreach ($this->data['scheduled_tests'] as $i => $test)
			{
				if ($test->id == $this->data['id_event'])
				{
					$this->data['event'] = $test;
				}
			}
		}
		//pr($this->data['scheduled_tests']);
		//pr($this->data['event']);
		//pr($this->data['scheduled_tests']);
		$config = array('is_personal' => 1, 'filter_portfolio' => true);
		$this->test_model->search($config);
		
		$this->data['cnd_fname'] = $this->input->post('cnd_fname');
		$this->data['cnd_lname'] = $this->input->post('cnd_lname');
		$this->data['cnd_email'] = $this->input->post('cnd_email');
		if (empty($this->data['cnd_email']))
		{
			$this->data['candidates'] = array( '0' => array('fname' => '', 'lname' => '', 'email' => '') );
		}
		else
		{
			foreach ($this->data['cnd_email'] as $i => $email)
			{
				$email = $email;
				$fname = $this->data['cnd_fname'][$i];
				$lname = $this->data['cnd_lname'][$i];
				$this->data['candidates'][] = array('fname' => $fname, 'lname' => $lname, 'email' => $email);
			}
		}

		$this->data['step'] = 1;
		
		if ($this->input->post('step1'))
		{
			$rules = array('name', 'job', 'date_scheduled', 'is_email');
      		$this->validation->set_rules($this->test_event_model->getRules($rules));
//			echo $scheduled = $this->input->post('id_tests');
//pr($_POST);

      		if ($this->validation->run() === TRUE)
      		{
      			
				$item = array();
				$item['id_companies']	= $this->auth->getID();
				$item['name']			= $this->input->post('name');
				$item['job']			= $this->input->post('job');
				$item['date_scheduled']	= $this->input->post('date_scheduled');
				$item['is_email']		= ($this->input->post('is_email') == 1) ? $this->input->post('is_email') : 0;

				if ($id_event = $this->test_event_model->insert($item))
				{				
					$config = array('is_personal' => -1, 'id_users' => $this->auth->getID());
					$this->data['scheduled_tests'] = $this->test_model->searchSchedule($config);
			
					$this->data['id_event'] = $id_event;
			
					if($this->data['id_event'])
					{
						//pr($this->data['scheduled_tests']);
						
						foreach ($this->data['scheduled_tests'] as $i => $test)
						{
							if ($test->id == $this->data['id_event'])
							{
								$this->data['event'] = $test;
							}
						}

						//pr($this->data['event']);
					}
		
					if (!empty($this->data['cnd_email']))
					{
						foreach ($this->data['cnd_email'] as $i => $email)
						{
							if ($this->data['cnd_fname'][$i] || $this->data['cnd_lname'][$i])
							{
								$item2 = array();
								$item2['id_events'] 	= $id_event;
								$item2['first_name']	= $this->data['cnd_fname'][$i];
								$item2['last_name']		= $this->data['cnd_lname'][$i];
								$item2['email'] 		= $email;
								$item2['date_created'] 	= date('Y-m-d H:i:s');
								$item2['code_event'] 	= substr(md5($item2['first_name'] . $item2['last_name'] . time()), 0, 11);
								$item2['code_event'] 	= substr($item2['code_event'], 0, 3) . '-' . substr($item2['code_event'], 3, 4) . '-' . substr($item2['code_event'], 7, 4); 
								
								$this->db->insert('candidates', $item2);
								
								if ($item['is_email'] == 1)
								{
									$subject = $item['name'] .' - '. $item['job'];
				    				$message = "Dear ".$item2['first_name']." ".$item2['last_name'].".<br />									 
											    A test event has been scheduled for you by: ".$this->auth->getUserData('first_name')." ".$this->auth->getUserData('last_name').". You will need to click on the link to the Testing Center below, or you can enter the URL in your Web browser.<br /><br />
				     						    Please use the following information to access your test.<br /><br />
				     						    <strong>Testing center:</strong> <a target='_blank' href='".$this->config->item('site_url')."'>".$this->config->item('site_url')."</a>.<br />
				     						    <strong>Your Test Event ID:</strong> ".$item2['code_event']."<br />
				     						    <strong>For Help</strong>, please visit: <a target='_blank' href='".$this->config->item('site_url') . $this->config->item('base_url')."content/help/'>".$this->config->item('site_url') . $this->config->item('base_url')."content/help/</a>.<br /><br /> 
				     
				    							Sincerely,<br />
												Website Administration."; 

				    				$this->load->library('email');	
									$config['mailtype'] = 'html';
									$config['protocol'] = 'mail';
									$config['charset'] = 'utf-8';
									$config['newline'] = '\r\n';
				
									$this->email->initialize($config);
									$this->email->from($this->config->item('site_email'), EMAIL_FROM_NAME);
									$this->email->to($item2['email']);					
									$this->email->subject($subject);
									$this->email->message($message);												
									$this->email->send();
								}
							}
						}
					}
					
					 $scheduled = $this->input->post('id_tests');
					 if (!empty($scheduled) && $scheduled[0] == ',') 
					 {
					 	$scheduled = substr($scheduled, 1, strlen($scheduled));
					 	$scheduled = explode(',', $scheduled);
					 	$scheduled = array_unique($scheduled);
					 	foreach($scheduled as $id_test)
					 	{
					 		$item3 = array();
							$item3['id_tests']  = trim($id_test);
							$item3['id_events'] = trim($id_event);
							
							$this->db->insert('tests_scheduled', $item3);
					 	}
					 }
					 else
					 {
					 	$scheduled = array();
					 }
					 
					 $this->data['step'] = 2;
					 redirect('/schedule/summary/'.$id_event);
				}
      		}
		}	
		else if ($this->input->post('step2'))
		{
			$this->data['step'] = 3;
		}
		//pr($_POST);
		//pr($this->data['candidates']);
		$this->renderLayout();
	}
	
	function summary($id_event = null)
	{
		//pr($_POST);
		$this->data['id_event']  = ($this->input->get_post('id_event')) ? $this->input->get_post('id_event') : $id_event;
		$this->data['event'] = $this->test_event_model->get($id_event);

		$fields = array('name' => T_('Category Name'));
        $this->data['treehtml'] = $this->cats->getTreeAsSchedule($fields);
        
        $config = array('is_personal' => 1);
		$this->test_model->search($config);
		
		$this->data['tests'] = $this->db->query('SELECT t.name, t.value AS price, (SELECT COUNT(*) FROM candidates c WHERE c.id_events=ts.id_events) AS num_candidates
												 FROM tests_scheduled ts, tests t 
												 WHERE ts.id_tests=t.id AND ts.id_events='.$this->db->escape($this->data['id_event']))->result_array();

		$config = array('is_personal' => -1, 'id_users' => $this->auth->getID());
		$this->data['scheduled_tests'] = $this->test_model->searchSchedule($config);
		
		$this->data['num_units'] = (!empty($this->data['tests'])) ? count($this->data['tests']) : 0;
		$this->data['num_candidates'] = (!empty($this->data['tests'][0]['num_candidates'])) ? $this->data['tests'][0]['num_candidates'] : 0;
		$this->data['total_tests'] = $this->data['num_units'] * $this->data['num_candidates']; 
		
		$this->load->library('Paypal');
		// Create an instance of the paypal library
		$myPaypal = new Paypal();
		
		// Specify your paypal email
		$myPaypal->addField('business', $this->config->item('paypal_email'));

		// Specify the currency
		$myPaypal->addField('currency_code', 'USD');
		
		// Specify the url where paypal will send the user on success/failure
		$myPaypal->addField('return', $this->config->item('site_url') . $this->config->item('base_url') . "schedule/success");
		$myPaypal->addField('cancel_return', $this->config->item('site_url') . $this->config->item('base_url') . "schedule/failure");
		
		// Specify the url where paypal will send the IPN
		$myPaypal->addField('notify_url', $this->config->item('site_url') . $this->config->item('base_url') . "schedule/ipn");
		
		//pr($this->data['tests']);
		// Specify the product information
		$this->data['total_price'] = 0;
		foreach($this->data['tests'] as $i => $test)
    	{
    		$myPaypal->addField('item_name', 	$test['name']);
			$myPaypal->addField('amount', 		$test['price']);
			$myPaypal->addField('item_number', 	$i+1);
			$this->data['total_price'] += $test['price'];
    	}
		
    	/*$myPaypal->addField('num_units', $this->data['num_units']);
    	$myPaypal->addField('num_candidates', $this->data['num_candidates']);
    	$myPaypal->addField('total_tests', $this->data['total_tests']);*/
    	
		// Specify any custom value
		//$myPaypal->addField('custom', 'muri-khao');
		
		// Enable test mode if needed
		$myPaypal->enableTestMode();
		
		// Let's start the train!
		//$this->data['payment_form'] = $myPaypal->submitPayment();
		$this->data['payment_form'] = $this->load->view('/payment/checkout_form');
		
		/*$userdata = $this->auth->getUserData();
		$userdata['purchase'] = '1';
		//pr($userdata);
		$this->auth->setUserData($userdata);*/
		
		/*
		$billing['id_user'] = $this->auth->getID();
		$billing['num_units'] = $this->data['num_units'];
		$billing['num_candidates'] = $this->data['num_candidates'];
		$billing['total_tests'] = $this->data['total_tests'];
		$billing['amount'] = $this->data['total_price'];
		$billing['date_created'] = date('Y-m-d H:i:s');
		$billing['id_events'] = $this->data['id_event'];
		
		$this->db->insert('billing', $billing);*/
		
		$this->renderLayout();
	}
	
	function portfolio($id_test)
	{
		$config = array('id_companies' => $this->auth->getID());
		$this->data['battery_tests'] = $this->test_model->searchBattery($config);
		
		$fields = array('name' => T_('Category Name'));
        $this->data['treehtml'] = $this->cats->getTreeAsSchedule($fields);
        
		$this->data['test'] = $this->test_model->get($id_test);

		$this->data['sample_questions'] = $this->db->query('SELECT * FROM tests_questions WHERE id_tests='.$id_test.' LIMIT 2')->result();
		if (!empty($this->data['sample_questions']))
		{
			foreach($this->data['sample_questions'] as $question)
			{
				$this->data['options'][] = $this->db->query('SELECT * FROM tests_answers WHERE id_tests_questions='.$question->id)->result();
			}
		}

		$config = array('is_personal' => 1);
		$this->test_model->search($config);
		
		$this->renderLayout();
	}
	
	function battery()
	{
		$fields = array('name' => T_('Category Name'));
        $this->data['treehtml'] = $this->cats->getTreeAsSchedule($fields);
        
        $config = array('id_companies' => $this->auth->getID());
		$this->data['battery_tests'] = $this->test_model->searchBattery($config);
		
		/*$this->data['test'] = $this->test_model->get($id_test);

		$this->data['sample_questions'] = $this->db->query('SELECT * FROM tests_questions WHERE id_tests='.$id_test.' LIMIT 2')->result();
		if (!empty($this->data['sample_questions']))
		{
			foreach($this->data['sample_questions'] as $question)
			{
				$this->data['options'][] = $this->db->query('SELECT * FROM tests_answers WHERE id_tests_questions='.$question->id)->result();
			}
		}
*/
		$config = array('is_personal' => 1);
		$this->test_model->search($config);
		
		if ($this->input->post('save'))
		{
			$rules = array('name');
      		$this->validation->set_rules($this->test_battery_model->getRules($rules));

      		if ($this->validation->run() === TRUE)
      		{      			
				 $scheduled = $this->input->post('id_tests');
				 if (!empty($scheduled) && $scheduled[0] == ',') 
				 {
				 	$item = array();
					$item['id_companies'] = $this->auth->getID();
					$item['name']		  = $this->input->post('name');
						
					$id_battery = $this->db->insert('tests_batteries', $item);
						
				 	$scheduled = substr($scheduled, 1, strlen($scheduled));
				 	$scheduled = explode(',', $scheduled);
				 	$scheduled = array_unique($scheduled);
				 	foreach($scheduled as $id_test)
				 	{
				 		$item = array();
						$item['id_tests']  = trim($id_test);
						$item['id_tests_batteries'] = $id_battery;
						
						$this->db->insert('tests_batteries_tests', $item);
				 	}
				 }
      		}
		}
		
		$this->renderLayout();
	}
	
	function process_sale()
	{
        $this->load->library('my_payment');
            
        $params->cc = '4242424242424242';
        $params->exp = '02/10';
        $params->desc = 'Some Product Here';
        $params->amount = '2.34';
        $params->firstName = 'Jowy';
        $params->lastName = 'Hurtado';
        $params->address = '1234 5th St.';
        $params->city = 'YourTown';
        $params->state = 'NM';
        $params->zip = '81225';
        $params->customerMonth = '07';
        $params->customerDay = '21';
        $params->customerYear = '11';
        $params->specialCode = '000';
            
        $result = $this->my_payment->authorize($params);
        
        print_r($result);
        echo "xxx";
die;
		/*
		$this->load->library('Paypal');
		// Create an instance of the paypal library
		$myPaypal = new Paypal();
		
		// Specify your paypal email
		$myPaypal->addField('business', 'doneb_1295944583_per@gmail.com');
		
		// Specify the currency
		$myPaypal->addField('currency_code', 'USD');
		
		// Specify the url where paypal will send the user on success/failure
		$myPaypal->addField('return', 'http://paypal.ua/paypal_success.php');
		$myPaypal->addField('cancel_return', 'http://paypal.ua/paypal_failure.php');
		
		// Specify the url where paypal will send the IPN
		$myPaypal->addField('notify_url', 'http://paypal.ua/paypal_ipn.php');
		
		// Specify the product information
		$myPaypal->addField('item_name', 'T-Shirt');
		$myPaypal->addField('amount', '9.99');
		$myPaypal->addField('item_number', '001');
		
		// Specify any custom value
		$myPaypal->addField('custom', 'muri-khao');
		
		// Enable test mode if needed
		$myPaypal->enableTestMode();
		
		// Let's start the train!
		$this->data['form'] = $myPaypal->submitPayment();
		
		$this->renderLayout();
		*/
	}
	
	function success()
	{
		$this->ipn();
		$this->renderLayout();
	}
	
	function failure()
	{
		$this->renderLayout();
	}
	
	function ipn()
	{
		$this->load->library('Paypal');
		
		// Create an instance of the paypal library
		$myPaypal = new Paypal();
		
		// Log the IPN results
		$myPaypal->ipnLog = TRUE;
		
		// Enable test mode if needed
		$myPaypal->enableTestMode();
		//pr($myPaypal);
		// Check validity and write down it
		if ($myPaypal->validateIpn())
		{
		    if ($myPaypal->ipnData['payment_status'] == 'Completed')
		    {
		         file_put_contents($this->config->item('site_url').'/files/paypal.txt', 'SUCCESS');
		    }
		    else
		    {
		         file_put_contents($this->config->item('site_url').'/files/paypal.txt', "FAILURE\n\n" . $myPaypal->ipnData);
		    }
		}

		//$this->renderLayout();
	}
	
	function add_portfolio($id_test)
	{
		$item['id_companies'] = $this->auth->getID();
        $item['id_tests']     = $id_test;
        $count = $this->db->query('SELECT COUNT(id_tests) AS num FROM tests_portfolio WHERE id_tests='.$item['id_tests'].' AND id_companies='.$item['id_companies'])->row();
        
        if ($count->num == 0)
        {
            $this->db->insert('tests_portfolio', $item);       	
        }
 
        $count = $this->db->query('SELECT COUNT(id_tests) AS num FROM tests_portfolio WHERE id_companies='.$item['id_companies'])->row();

        echo $count->num; 		
	}
	
  function edit($id = null)
  {
    if (!empty($id))
    {     
      $object = $this->db->query('SELECT * FROM tests_events WHERE id='.$this->db->escape($id))->row();
      
      if (!count($object))
      {
        $this->data['view'] = '_elements/query_no_object';
        $this->load->view($this->data['layout'], $this->data);
  
        return false; 
      }
      
      $this->data['event'] = $object;
      $this->data['candidates'] = $this->db->query('SELECT * FROM candidates WHERE id_events='.$this->db->escape($object->id))->result_array();
      //pr($this->data['candidates']);
      
      if (!count($_POST))
      {
        $this->validation->id_event		= $object->id;
        $this->validation->name 		= $object->name;
        $this->validation->date_scheduled = $object->date_scheduled;
        $this->validation->job 			= $object->job; 
      }
      else
      {
      	/*
	        $this->data['categorySelect'] = $this->cats->getCategorySelect("id_parent", $this->input->post('id_parent'));
	        
	       	$rules = array('first_name', 'last_name', 'id_parent', 'time', 'shuffle', 'type', 'value', 'tags', 'status', 'private', 'reject');
	        $this->validation->set_rules($this->test_model->getRules($rules));
	        
	        $this->validation->set_message('__nameFree', '<span class="black bold">«'.T_("Test").'»</span> '.T_("already exists with such Name. Please change the Name."));
	        $this->validation->set_message('__category', T_('You should select active Test Category.'));
	        
	        if ($this->validation->run() === TRUE)
	        {
	          	$item['id']   			= (int)$this->validation->id;
	 			$item['name'] 			= $this->validation->name;
		        $item['description'] 	= $this->validation->description;
		        $item['id_tests_categories'] = $this->validation->id_parent;
		        $item['time'] 			= $this->validation->time;
		        $item['shuffle'] 		= $this->validation->shuffle;
		        $item['type'] 			= $this->validation->type;
		        $item['value'] 			= $this->validation->value;
		        $item['tags'] 			= $this->validation->tags;
		        $item['status'] 		= $this->validation->status;
		        $item['id_contributor'] = $this->validation->id_contributor;
		        $item['private'] 		= $this->validation->private;
		        $item['reject'] 		= $this->validation->reject;
	          
	            $this->test_model->update($item);
	            
	            $filter = (!empty($_POST['sample_questions'])) ? implode(',', $_POST['sample_questions']) : '';
	            $filter1 = ($filter) ? ' AND id NOT IN ('.$filter.')' : '';
	            $this->db->query('UPDATE tests_questions SET is_sample=0 WHERE id_tests='.$this->db->escape($this->validation->id).$filter1);
	            if (!empty($filter))
	            {
	                $this->db->query('UPDATE tests_questions SET is_sample=1 WHERE id_tests='.$this->db->escape($this->validation->id).' AND id IN ('.$filter.')');	
	            }
	            
	*/
	            redirect('/');
	       // }
      }     
    }
    
    //$this->data['Title'] .= ' / ' . T_('Tests') . ' / ' . T_('Edit Test') . ' / ' . $object['name'];
    $this->renderLayout();
  }
}
?>